import {
	addUserHelmet,
	getUserHelmet
} from '@/api/user.js'


var deviceId = '' //设备id
var readyservices = '' //服务id
var services = '' //服务id
var writeUuid = '' //uuid
var notifyUuid = '' //接受uuid
// var uuid = '' //判断连接设备
var name = '' //判断连接设备
var oid = '' //头盔绑定接口
var time = null

const data = {
	// 初始化蓝牙
	player(blueName, uid) {
		return new Promise((resolve, reject) => {
			var that = this;
			// uuid = bluekeyUuid //判断连接设备
			name = blueName //判断连接设备
			oid = uid //判断连接设备
			console.log(name, uid, '传入数据')
			getUserHelmet({}).then(res => {
				if (res.status == 200) {
					if (res.data) {
						console.log('已有头盔')
						that.initialization()
					} else {
						console.log('没有头盔')
						if (oid) {
							console.log('没有头盔有')
							//连接成功则发送给后端
							addUserHelmet({
								uid: oid
							}).then(k => {
								if (k.status == 200) {
									console.log('绑定头盔成功')
									uni.setStorageSync('singleShow', true);
									resolve({
										success: true,
										show: true,
										msg: k.msg
									})
									that.initialization()
								} else {

									resolve({
										success: false,
										show: true,
										msg: k.msg
									})
									// that.config.Toast(res.msg)
								}

							})

						} else {
							that.initialization()
						}
					}
				} else {
					that.config.Toast(res.msg)
				}
			})

		})
	},
	initialization() {
		var that = this;
		uni.openBluetoothAdapter({ //调用微信小程序api 打开蓝牙适配器接口
			success: function(res) {
				// console.log(res)
				// uni.showToast({
				// 	title: '初始化成功',
				// 	icon: 'success',
				// 	duration: 800
				// })

				that.findBlue(); //2.0
			},
			fail: function(res) { //如果手机上的蓝牙没有打开，可以提醒用户

				uni.showToast({
					title: '请打开蓝牙',
					type: 'error',
					duration: 5000
				});

			}
		})
		// that.findBlue(); //2.0
	},
	findBlue() {
		var that = this
		uni.startBluetoothDevicesDiscovery({
			allowDuplicatesKey: false,
			interval: 0,
			success: function(res) {
				console.log(res, '搜索')
				// uni.showLoading({
				// 	title: '正在搜索设备',
				// })
				that.getBlue() //3.0
				that.connectionStatus = '连接中'
			}
		})
	},
	getBlue() {
		var that = this
		time = setTimeout(() => {
			//uni.getBluetoothDevices获取在蓝牙模块生效期间所有已发现的蓝牙设备。包括已经和本机处于连接状态的设备
			uni.getBluetoothDevices({

				success: function(res) {
					if (res.devices.length != 0) {
						console.log(res.devices, '附近蓝牙列表')
						res.devices.forEach(k => {
							console.log(k.localName, '附近蓝牙名称')
							if (k.localName) {
								if (name.toUpperCase() === k.localName.toUpperCase()) {
									console.log(name.toUpperCase(), k.localName
										.toUpperCase(),
										'想通')
									that.connetBlue(k.deviceId)
									deviceId = k.deviceId;

								} else {
									// that.findBlue() //3.0
								}
							}
							// console.log(name.toUpperCase(), k.name.toUpperCase(), '想通')
							//判断二维码上的name是否与蓝牙name一致

						})
					} else {
						that.getBlue() //3.0
					}
					//将BluetoothList遍历给用户，当用户点击连接某个蓝牙时调用4.0
				},
				fail: function() {
					console.log("搜索蓝牙设备失败")
				}
			})
		}, 1000)

	},
	connetBlue(dId) {
		console.log(deviceId, dId, 'deviceId')
		return new Promise((resolve, reject) => {
			var that = this;

			uni.createBLEConnection({
				// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
				deviceId: dId, //设备id
				success: function(res) {
					uni.showToast({
						title: '连接成功',
						icon: 'fails',
						duration: 800
					})

					// uni.hideLoading();
					clearTimeout(time)
					console.log(oid, "连接蓝牙成功!-->11111")
					uni.stopBluetoothDevicesDiscovery({
						success: function(res) {
							console.log('连接蓝牙成功之后关闭蓝牙搜索');
						}
					})
					that.getServiceId() //5.0
				}
			})
		})
	},
	getServiceId() {
		var that = this

		uni.getBLEDeviceServices({
			// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
			deviceId: deviceId,
			success: function(res) {
				console.log(res.services, 'services')
				//需要什么服务就用对应的services 
				readyservices = res.services[0].uuid //因设备而议：该特征值只支持读
				if (res.services.length == 3) {
					services = res.services[0].uuid //因设备而议：该特征值支持write和notfy服务
					that.getCharacteId() //6.0
				} else {
					services = res.services[0].uuid //因设备而议：该特征值支持write和notfy服务
					that.getCharacteId() //6.0
				}


			}
		})
	},
	getCharacteId() {
		var that = this
		uni.getBLEDeviceCharacteristics({
			// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
			deviceId: deviceId,
			// 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
			serviceId: services,
			// serviceId: that.serviceList[0].needUseService[0].serviceUUID,
			success: function(res) {
				console.log(res, '服务')
				for (var i = 0; i < res.characteristics.length; i++) { //2个值
					var model = res.characteristics[i]
					if (model.properties.write) {
						// this.sendMy()给设备写入
						writeUuid = model.uuid

						that.sendMy('', 'BEBB020101') //开机指令

						// console.log('BEBB020101', '开机')
						// console.log(uni.getStorageSync('singleShow'), 'singleShow')
						const singleShow = uni.getStorageSync('singleShow')
						if (singleShow) {
							// console.log(uni.getStorageSync('singleShow'), '可以')
							const phone = uni.getStorageSync('phone')
							var one = phone.substring(7, 8)
							var two = phone.substring(8, 9)
							var three = phone.substring(9, 10)
							var four = phone.substring(10, 11)
							// console.log(one, two, three, four,
							// 	'llllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllll')
							that.sendMy('',
								`BEBB0502${that.numToBytes(Number(one),2)}${that.numToBytes(Number(two),2)}${that.numToBytes(Number(three),2)}${that.numToBytes(Number(four),2)}`
							) //链接蓝牙先发配对码
						}

						setTimeout(() => {
							that.sendMy('', 'BEBB020206') //查询蓝牙连接状态
						}, 1000)


					}
					if (model.properties.notify) {
						//model.uuid:用来notify的uuid值
						notifyUuid = model.uuid
						that.startNotice()
					}

				}
			}
		})
	},
	//buffer允许写入的uuid level等级或者配对码
	sendMy(str, level) {
		// console.log(str, level, 'jjjjjj')
		return new Promise((resolve, reject) => {
			var that = this
			if (str) {
				var arr = ['BEBB0100']
				if (str == 3) {
					arr[1] = `BEBB0101`; //新手求带
					// console.log('BEBB0101', '新手')
				} else if (str == 2) {
					// var buff = that.string2buffer(`BEBB0102`); //高手收徒
					arr[1] = `BEBB0102`; //高手收徒
					// console.log('BEBB0102', '高手收徒')
				} else if (str == 4) {
					// var buff = that.string2buffer(`BEBB0103`); //动感音乐
					arr[1] = `BEBB0103`; //动感音乐
					// console.log('BEBB0103', '动感音乐')
				} else if (str == 1) {
					// console.log(`BEBB0203${that.numToBytes(level,2)}`, '等级等效需传入自身等级')
					// var buff = that.string2buffer(`BEBB0203${that.str_to_hex(level)}`); //等级等效需传入自身等级
					arr[1] = `BEBB0203${that.numToBytes(level,2)}`; //动感音乐
				}
				arr.forEach(k => {
					var buff = that.string2buffer(k); //动感音乐
					//this.string2buffer-->字符串转换成ArrayBufer（设备接收数据的格式ArrayBufer）
					uni.writeBLECharacteristicValue({
						// 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
						deviceId: deviceId,
						// 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
						serviceId: services,
						// 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
						// characteristicId: buffer, //第二步写入的特征值
						characteristicId: writeUuid,
						// 	.writeCharacteristicsId, //第二步写入的特征值
						// 这里的value是ArrayBuffer类型
						value: buff,
						success: function(res) {
							//此时设备已接收到你写入的数据
							console.log(res, "写入成功")
							// that.startNotice()
						},
						fail: function(err) {
							// console.log(err, 'err')
						},
						complete: function() {
							// console.log("调用结束");
						}
					})
				})
			} else {

				console.log(level, '进入2222')
				// var arr = ['BEBB020201', `BEBB0502${that.numToBytes(Number(level),8)}`] //开机命令 查询蓝牙连接状态
				var buff = that.string2buffer(level); //动感音乐
				//this.string2buffer-->字符串转换成ArrayBufer（设备接收数据的格式ArrayBufer）
				uni.writeBLECharacteristicValue({
					// 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
					deviceId: deviceId,
					// 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
					serviceId: services,
					// 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
					// characteristicId: buffer, //第二步写入的特征值
					characteristicId: writeUuid,
					// 	.writeCharacteristicsId, //第二步写入的特征值
					// 这里的value是ArrayBuffer类型
					value: buff,
					success: function(res) {
						//此时设备已接收到你写入的数据
						console.log(res, "写入成功")
						resolve({
							msg: '发送成功'
						})
						// that.startNotice()
					},
					fail: function(err) {
						// console.log(err, 'err')
					},
					complete: function() {
						// console.log("调用结束");
					}
				})

			}

		})

	},
	startNotice() {
		var that = this;
		uni.notifyBLECharacteristicValueChange({
			state: true, // 启用 notify 功能
			// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接 
			deviceId: deviceId,
			// 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
			serviceId: services,
			// 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
			characteristicId: notifyUuid, //第一步 开启监听 notityid  第二步发送指令 write
			success(res) {
				console.log(res, '接受消息')
				//接收蓝牙返回消息
				// uni.onBLECharacteristicValueChange((sjRes) => {
				// 	// 此时可以拿到蓝牙设备返回来的数据是一个ArrayBuffer类型数据，
				// 	// 判断点击开始后再接受数据 收到设备回复的空闲时需要设置为false
				// 	var nonceId = that.ab2hex(sjRes.value) //10.0
				// 	console.log(sjRes, 'sendMy')
				// 	console.log('194行' + nonceId)
				// 	// that.$store.commit('status', nonceId)
				// 	uni.setStorageSync('status', nonceId.substring(8, 10));

				// })
			},
			fail(err) {
				console.log(err)
			}
		})
	},
	disconnect() {
		var that = this
		uni.closeBLEConnection({
			deviceId: deviceId,
			success: function(res) {
				console.log('蓝牙连接已断开');
				that.clearPreviousBluetoothInit()
			},
			fail: function(err) {
				console.log('蓝牙断开连接失败', err);
			}
		});
	},

	string2buffer(str) {
		let val = ""
		if (!str) return;
		let length = str.length;
		let index = 0;
		let array = []
		while (index < length) {
			array.push(str.substring(index, index + 2));
			index = index + 2;
		}
		val = array.join(",");
		// 将16进制转化为ArrayBuffer
		return new Uint8Array(val.match(/[\da-f]{2}/gi).map(function(h) {
			return parseInt(h, 16)
		})).buffer
	},
	// 16进制转10
	string16to10(e) {
		let decimalNumber = parseInt(e, 16);
		// console.log(decimalNumber); // 输出结果为：6703
		return decimalNumber
	},

	// 解码收到的数据
	ab2hex(buffer) {
		const hexArr = Array.prototype.map.call(
			new Uint8Array(buffer),
			function(bit) {
				return ('00' + bit.toString(16)).slice(-2)
			}
		)
		return hexArr.join('')
	},
	//字符串转16进制码
	str_to_hex(str) {
		return str.toString(16);
	},
	// 转四字节转八位
	numToBytes(str, num) {
		var value = str.toString(16);
		var k = ''
		if (value.length < num) {
			var b = num - value.length
			for (var f = 0; f < b; f++) {
				k += '0'
			}
		}
		return k + value
	},
	// 清除上一次蓝牙初始化的方法
	clearPreviousBluetoothInit() {
		// 关闭蓝牙适配器
		uni.closeBluetoothAdapter({
			success: function(res) {
				console.log('蓝牙适配器已关闭');
			},
			fail: function(err) {
				console.log('关闭蓝牙适配器失败:', err);
			}
		});

		// 重置所有蓝牙模块的状态
		uni.setBluetoothAdapterState(false);

		// 清除搜索到的设备列表
		uni.clearBluetoothDevices();

	}

}
export default data